//
//  YCDatePickerView.m
//  DemoPickerView
//
//  Created by tangkexiong on 16/3/9.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCDatePickerView.h"

@interface YCDatePickerView () {
    UIWindow *_window;
    UIWindow *_oldWindow;
}

@end

@implementation YCDatePickerView

#pragma mark - UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Control

- (void)_show {
    if ([_myDelegate respondsToSelector:@selector(datePickerViewWillShow:)]) {
        [_myDelegate datePickerViewWillShow:self];
    }
    
    [self _showAnimation];
}

- (void)_dismiss {
    if ([_myDelegate respondsToSelector:@selector(datePickerViewWillDismiss:)]) {
        [_myDelegate datePickerViewWillDismiss:self];
    }
    
    [self _dismissAnimation];
}

- (void)_showAnimation {
    _constraintDlgViewBottom.constant = 0.f;
    _bgView.alpha = 0.f;
    [UIView animateWithDuration:0.3f animations:^{
        _bgView.alpha = 0.5f;
        
        [self.view layoutIfNeeded];
    }];
}

- (void)_dismissAnimation {
    _constraintDlgViewBottom.constant = -260.f;
    [UIView animateWithDuration:0.3 animations:^{
        _bgView.alpha = 0;
        
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        [_window resignKeyWindow];
        _window = nil;
        
        [_oldWindow makeKeyAndVisible];
    }];
}

#pragma mark - IBAction

- (IBAction)cancelBtnClicked:(id)sender {
    [self _dismiss];
}

- (IBAction)commitBtnClicked:(id)sender {
    [self _dismiss];
    
    if ([_myDelegate respondsToSelector:@selector(datePickerView:didSelectDate:)]) {
        [_myDelegate datePickerView:self didSelectDate:_datePickerView.date];
    }
}

- (IBAction)bgViewClikced:(id)sender {
    [self _dismiss];
}

#pragma mark - Private

- (void)_configView {
    _bgView.backgroundColor = [UIColor blackColor];
    _bgView.alpha = 0.f;
    
    
    _constraintDlgViewBottom.constant = -260.f;
    
    [self.view layoutIfNeeded];
}

#pragma mark - Public 

+ (instancetype)instanceWithDelegate:(id<YCDatePickerViewDelegate>)delegate {
    YCDatePickerView *pickerView = [[YCDatePickerView alloc] initWithNibName:@"YCDatePickerView" bundle:nil];
    
    pickerView.myDelegate = delegate;
    
    return pickerView;
}

- (void)show {
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.windowLevel = 440.f;
    _window.rootViewController = self;
    _oldWindow = [UIApplication sharedApplication].keyWindow;
    [_window makeKeyAndVisible];
    
    [self _configView];
    
    [self _show];
}


@end
